from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    # 用户角色选择
    ROLE_CHOICES = (
        ('admin', '管理员'),
        ('technician', '维修技术人员'),
        ('customer', '客户'),
        ('receptionist', '前台'),
        ('quality_checker', '质检员'),
    )
    
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='customer', verbose_name='用户角色')
    phone = models.CharField(max_length=20, blank=True, verbose_name='联系电话')
    address = models.TextField(blank=True, verbose_name='地址')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'

    def __str__(self):
        return f"{self.user.username} - {self.get_role_display()}"

# 信号：创建用户时自动创建Profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
